# -*- coding: utf-8 -*-
"""
Created on 2025/7/5 15:34
---------
@summary: 
---------
@author: rui_kai
"""
import os

from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn

from utils.excel_handler import ExcelHandlerNew
from utils.excel_read import ExcelRead
from utils.tools import set_save_path


class TemplateChange:
    EXPORT_PATH = "output"

    def __init__(self, required_headers, headers, file_path, suffix):
        self.required_headers = required_headers  # 需要的字段
        self.headers = headers  # 编写的header
        self.file_path = file_path  # 核价文件路径
        self.suffix = suffix  # 后缀

        self.stock = None
        self.excel = None
        self.total_rows = None
        self.console = Console()
        self.write_excel_path = os.path.splitext(os.path.basename(file_path))[0]

        self.run()

    def __start_callback(self):
        while True:
            stock = self.console.input(f"[bold green]请输入库存数量(回车默认2):[/bold green]") or 2
            try:
                self.stock = int(stock)
            except ValueError:
                self.console.print("[bold red]请输入数字[/bold red]")
                continue
            break

        self.console.print(f"[bold green]任务已经开始..请耐心等待...[/bold green]")
        # 开始检查是否是表格文件
        if not self.file_path.endswith(".xlsx"):
            self.console.print(f"[bold red]文件必须是xlsx文件[/bold red]")
            exit()

    def _open_excel(self):
        self.excel = ExcelRead(self.file_path)
        self.excel.load_workbook()
        self.total_rows = self.excel.sheet.max_row
        self.console.print(f"[bold green]文件共有 {self.total_rows} 行数据[/bold green]")

    def _verify_headers(self):
        headers = []
        for row in self.excel.sheet.iter_rows(min_col=1, max_col=11):
            headers = [cell.value for cell in row]
            break

        missing = [h for h in self.required_headers if h not in headers]
        if missing:
            self.console.print(f"[bold red]缺少以下字段: {', '.join(missing)}[/bold red]")
            return

        return True

    def run(self):
        self.__start_callback()
        self._open_excel()
        if not self._verify_headers():
            return

        self.write_excel()

    def write_excel(self):
        save_file_path = set_save_path(f"{self.write_excel_path}_{self.suffix}", "xlsx", self.__class__.EXPORT_PATH)
        print(save_file_path)
        write_excel = ExcelHandlerNew(save_file_path)
        write_excel.write_head(self.headers)

        with Progress(
                SpinnerColumn(),
                TextColumn("[progress.description]{task.description}"),
                BarColumn(),
                TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
                TimeRemainingColumn()
        ) as progress:
            task = progress.add_task("[cyan]处理数据中...", total=self.total_rows - 1)  # 减去标题行
            for row in self.excel.sheet.iter_rows(min_row=2, min_col=1, max_col=11):
                write_excel.write_row(self.__get_row_data(row))
                progress.update(task, advance=1)

        self.console.print(f"[bold green]当前任务开始保存[/bold green]")
        write_excel.save()
        self.console.print(f"[bold green]保存成功[/bold green]")

    def __get_row_data(self, row):
        if "家速云" in self.suffix:
            return [
                row[0].value, row[4].value, self.stock, row[0].value, "", "", "", "", row[6].value
            ]
        else:
            return [
                row[0].value, self.stock, row[4].value, row[0].value, "", row[6].value, ""
            ]
